<template>
  <div class="employee">
    <basic-container>
      <avue-tabs :option="option"
                 @submit="nextStep"
                 @change="change">
        <template slot="before">
          <avue-form v-if="load"
                     v-model="data"
                     :option="formOption"
                     @submit="upData">
            <template slot="roleName"
                      scope-slot="scope">
              <el-input v-model="data.roleName"
                        disabled
                        class="input-with-select">
                <el-button slot="append"
                           icon="el-icon-search"
                           @click.native="showRoleSelect"></el-button>
              </el-input>
            </template>
          </avue-form>
          <template v-if="type==='worked'">
            <avue-crud v-model="obj"
                       :data="workedData"
                       ref="crud"
                       :option="option1"
                       @selection-change="handleSelectionChange"
                       :table-loading="listLoading"
                       @row-save="handleSave"
                       @row-del="handleDel"
                       @row-update="handleUpdate">
              <template slot="menuLeft">
                <el-button type="primary"
                           @click="handleRowEdit"
                           size="small">编 辑</el-button>
                <el-button type="primary"
                           @click="handleRowDel"
                           size="small">删 除</el-button>
              </template>
            </avue-crud>
          </template>

          <template v-if="type==='family'">
            <avue-crud v-model="obj"
                       :data="familyData"
                       ref="crud"
                       :option="option2"
                       @selection-change="handleSelectionChange"
                       :table-loading="listLoading"
                       @row-save="handleSave"
                       @row-del="handleDel"
                       @row-update="handleUpdate">
              <template slot="menuLeft">
                <el-button type="primary"
                           @click="handleRowEdit"
                           size="small">编 辑</el-button>
                <el-button type="primary"
                           @click="handleRowDel"
                           size="small">删 除</el-button>
              </template>
            </avue-crud>
          </template>

        </template>
      </avue-tabs>
      <br />
      <!--角色选择界面-->
      <el-dialog title="门禁角色选择"
                 :visible.sync="roleSelectVisible"
                 :close-on-click-modal="false">
        <div style="height: 380px!important;position:relative">
          <div style="height: 260px;overflow: auto;">
            <roleTree ref="role_tree"
                      @treeNode-click="roleTreeNodeClick"></roleTree>
          </div>
          <div>
            <el-tag type="info"
                    style="position:absolute;bottom: 95px;"
                    size="small">选择的角色</el-tag>
          </div>
          <el-input type="textarea"
                    style="position:absolute;bottom: 0px;"
                    disabled
                    :rows="4"
                    v-model="textarea_role"></el-input>
        </div>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click.native="roleSelectVisible = false">取消</el-button>
          <el-button type="primary"
                     @click.native="roleSelectSubmit">确定</el-button>
        </div>
      </el-dialog>
    </basic-container>
  </div>

</template>
<script>
import request from "@/router/axios";
import option from "@/const/archives/index";
import option1 from "@/const/crud/employee_worked";
import option2 from "@/const/crud/employee_family";
import jbxxOption from "@/const/archives/jbxx";
import roleTree from "../zhgl/houseowner/roleTree.vue";
import {
  getObj,
  putObj,
  fetchDeptTree,
  fetchWorkedList,
  fetchFamilyList,
  addFamily,
  putFamily,
  delFamily,
  addWork,
  putWork,
  delWork
} from "@/api/archives";
import { validatenull } from "@/util/validate";
export default {
  name: "addemployee",
  components: {
    roleTree
  },
  data() {
    return {
      formOption: {},
      obj: {},
      workedData: [],
      familyData: [],
      option1: option1,
      option2: option2,
      load: true,
      imgUrl: [],
      id: "",
      type: "",
      submitdate: {},
      data: {},
      option: option,
      treeDeptData: [], //部门
      workings: [], //工作年限
      insurances: [], //是否缴纳保险
      educations: [], //学历
      positions: [], //职位
      textarea_role: "",
      textarea_role_arr: [],
      textarea_role_arr_des: [],
      roleSelectVisible: false,
      listQuery: {
        employee_id: ""
      }
    };
  },
  created: function() {
    this.id = this.$route.query.id;
    getObj(this.id).then(res => {
      this.data = res.data.data;
    });
    this.handleDept();
  },
  methods: {
    breaks() {
      // this.$router.$avueRouter.closeTag();
      // this.$router.push({ path: "/fymk/fygl" });
    },
    /**
     * 选择角色
     */
    showRoleSelect: function() {
      this.roleSelectVisible = true;
      var names = this.data.roleName.split(",");
      var ids = this.data.roleId.split(",");
      if (ids.length === names.length) {
        for (var b = 0; b < names.length; b++) {
          this.textarea_role_arr_des.push(names[b] + "@" + ids[b]);
        }
      }

      this.textarea_role = this.data.roleName;
      // = this.data.roleName.split(',')
      this.textarea_role_arr = this.data.roleId.split(",");
    },
    roleTreeNodeClick(data, node) {
      if (data.leaf) {
        var index = -1;
        for (var i = 0; i < this.textarea_role_arr_des.length; i++) {
          if (this.textarea_role_arr_des[i] == data.name + "@" + data.id) {
            index = i;
            break;
          }
        }
        if (index >= 0) {
          this.textarea_role_arr_des.splice(index, 1);
        } else {
          this.textarea_role_arr_des.push(data.name + "@" + data.id);
        }
        var textarea_role_arr_name = [];
        this.textarea_role_arr = [];
        for (var i = 0; i < this.textarea_role_arr_des.length; i++) {
          var fg = this.textarea_role_arr_des[i].split("@");
          this.textarea_role_arr.push(fg[1]);
          textarea_role_arr_name.push(fg[0]);
        }

        this.textarea_role = textarea_role_arr_name.join();
      }
    },
    roleSelectSubmit: function() {
      this.data.roleId = this.textarea_role_arr.join();
      this.data.roleName = this.textarea_role;
      this.roleSelectVisible = false;
    },
    /**
     * 编辑页面,查询此条数据
     */
    nextStep(next) {
      next();
    },
    upData() {
      this.submitdate = Object.assign({}, this.submitdate, this.data);
      //if (this.type == 'yxzl') {
      //this.submitdate = Object.assign({}, this.submitdate, this.data)
      this.submitdate.id = this.id;
      putObj(this.submitdate).then(response => {
        if (response.data.data) {
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
          // this.$router.$avueRouter.closeTag();
          this.breaks();
        }
      });
      // }
      //next()
    },
    change(item) {
      this.load = false;
      this.type = item.prop;
      this.formOption = item.form;
      this.listQuery.employee_id = this.id;
      this.$nextTick(() => {
        this.load = true;
      });
      if (this.type === "worked") {
        this.fetchWorkedList();
      } else if (this.type === "family") {
        this.fetchFamilyList();
      }
    },
    fetchWorkedList() {
      this.listLoading = true;
      fetchWorkedList(this.listQuery).then(response => {
        this.workedData = response.data.records;
        this.listLoading = false;
      });
    },
    fetchFamilyList() {
      this.listLoading = true;
      fetchFamilyList(this.listQuery).then(response => {
        this.familyData = response.data.records;
        this.listLoading = false;
      });
    },
    resetChange() {
      this.$message.success("清空方法回调");
    },
    handleRowEdit() {},
    /**
     * @title 当前选中的数据
     * @param val 选中的值
     *
     **/
    handleSelectionChange(val) {
      this.tableRow = val;
      this.$notify({
        showClose: true,
        message: JSON.stringify(val),
        type: "success"
      });
    },
    /**
     * 删除提醒
     */
    handleRowDel(row, index) {
      if (validatenull(this.tableRow)) {
        this.$notify({
          showClose: true,
          message: "请选择一行要删除的数据",
          type: "error"
        });
        return false;
      } else if (this.tableRow.length > 1) {
        this.$notify({
          showClose: true,
          message: "请选择一行数据，不要选择多行",
          type: "error"
        });
        return false;
      }

      this.handleDel(row, -1);
    },
    /**
     * @title 数据删除
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     *
     **/
    handleDel(row, index) {
      console.log(row);
      this.$confirm(
        `是否确认删除 ${row.name ? row.name : row.workName}`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          // this.tableData.splice(index, 1);
          if (this.type === "worked") {
            delWork(row.id).then(res => {
              this.$notify({
                showClose: true,
                message: "删除成功",
                type: "success"
              });
              this.fetchWorkedList();
            });
          } else if (this.type === "family") {
            delFamily(row.id).then(res => {
              this.$notify({
                showClose: true,
                message: "删除成功",
                type: "success"
              });
              this.fetchFamilyList();
            });
          }
        })
        .catch(err => {});
    },
    /**
     * 编辑提醒
     */
    handleRowEdit() {
      if (validatenull(this.tableRow)) {
        this.$notify({
          showClose: true,
          message: "请选择一行要编辑的数据",
          type: "error"
        });
        return false;
      } else if (this.tableRow.length > 1) {
        this.$notify({
          showClose: true,
          message: "请选择一行数据，不要选择多行",
          type: "error"
        });
        return false;
      }
      this.handleEdit(this.tableRow[0], -1);
    },
    handleEdit(row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    /**
     * @title 数据更新
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     * @param done 为表单关闭函数
     *
     **/
    handleUpdate(row, index, done) {
      if (this.type === "worked") {
        putWork(row).then(res => {
          if (!res.data) {
            this.$notify({
              title: "更新失败",
              message: "更新失败" + res.msg,
              type: "faile",
              duration: 2000
            });
            return false;
          }
          this.fetchWorkedList();
          this.$notify({
            title: "成功",
            message: "更新成功",
            type: "success",
            duration: 2000
          });
        });
      } else if (this.type === "family") {
        putFamily(row).then(res => {
          if (!res.data) {
            this.$notify({
              title: "更新失败",
              message: "更新失败" + res.msg,
              type: "faile",
              duration: 2000
            });
            return false;
          }
          this.fetchFamilyList();
          this.$notify({
            title: "成功",
            message: "更新成功",
            type: "success",
            duration: 2000
          });
        });
      }
      done();
    },
    /**
     * @title 数据添加
     * @param row 为当前的数据
     * @param done 为表单关闭函数
     *
     **/
    handleSave(row, done) {
      row.employeeId = this.id;
      if (this.type === "worked") {
        addWork(row).then(res => {
          if (!res.data) {
            this.$notify({
              title: "添加失败",
              message: "添加失败" + res.msg,
              type: "faile",
              duration: 2000
            });
            return false;
          }
          this.fetchWorkedList();
          this.$notify({
            title: "成功",
            message: "创建成功",
            type: "success",
            duration: 2000
          });
        });
      } else if (this.type === "family") {
        addFamily(row).then(res => {
          if (!res.data) {
            this.$notify({
              title: "添加失败",
              message: "添加失败" + res.msg,
              type: "faile",
              duration: 2000
            });
            return false;
          }
          this.fetchFamilyList();
          this.$notify({
            title: "成功",
            message: "创建成功",
            type: "success",
            duration: 2000
          });
        });
      }
      done();
    },
    //初始化数据字典
    initDictsData: function() {
      request.get("/admin/dict/type/insurance_status").then(res => {
        if (res.status === 200) {
          this.insurances = res.data;
        }
      });
      request.get("/admin/dict/type/working_status").then(res => {
        if (res.status === 200) {
          this.workings = res.data;
        }
      });
      request.get("/admin/dict/type/education_status").then(res => {
        if (res.status === 200) {
          this.educations = res.data;
        }
      });
      request.get("/admin/dict/type/position_status").then(res => {
        if (res.status === 200) {
          this.positions = res.data;
        }
      });
    },
    handleDept() {
      fetchDeptTree().then(response => {
        this.treeDeptData = response.data;
      });
    }
  },
  mounted() {
    //加载树
    // this.initDictsData()
  }
};
</script>
<style lang="scss">
</style>